package cn.android666.mediacodecsynchronous

import android.annotation.SuppressLint
import android.text.format.DateFormat
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.nio.channels.FileChannel

class H264Saver {

    private var fileChannel : FileChannel? = null

    init {
        @SuppressLint("SdCardPath")
        val fileDir = File("/sdcard/-0a/")
        var exists = fileDir.exists()

        if (!exists) {
            exists = fileDir.mkdir()
        }

        if (exists) {
            val fileName = "${DateFormat.format("yyyy_MM_dd_HHmmss", System.currentTimeMillis())}.h264"
            fileChannel = FileOutputStream(File(fileDir, fileName)).channel
        }
    }

    fun write(byteBuffer: ByteBuffer) {
        fileChannel?.write(byteBuffer)
    }

    fun close() {
        val channel = fileChannel
        if (channel != null) {
            try {
                channel.close()
            } catch (e: Exception) {
                Timber.e(e, "关闭fileChannel时出现异常")
            }
            fileChannel = null
        }
    }

}